<?php

namespace Home\Controller;
use Think\Controller;

/**
 * 前台公共控制器
 * 为防止多分组Controller名称冲突，公共Controller名称统一使用分组名称
 */
class HomeController extends Controller
{

  	/**
     * 空操作，用于输出404页面
     * @return [type] [description]
     * @author Weiliqiang <[<email address>]>
     */

  	public function _empty()
    {
  		$this->redirect('Index/index');
  	}

    /**
     * 控制器初始化
     * @return [type] [description]
     * @author Weiliqiang <[<email address>]>
     */
    protected function _initialize()
    {
        /* 读取站点配置 */
        $config = api('Config/lists');
        C($config); //添加配置

        if(!C('WEB_SITE_CLOSE')){
            $this->error('站点已经关闭，请稍后访问~');
        }

        // 包装分类导航数组，遍历至模板
        $info = D('classify')->where('status=1')->select();
        foreach($info as $key=>$val){
            $tmp[$val['id']] = $info[$key];
        }

        // 检测session
        $chek_session = $this->cheksession();

        $this->assign('chek_session',$chek_session);


        // 购物车的数量
        $user_id = I('session.')['onethink_home']['user_id'];
        $cart = M('cart');
        $map['user_id'] =  $user_id;
        $map['status'] = 0;
        $shop = $cart->where($map)->select();
        foreach ($shop as $countkey => $countval) {
            $shopcount += $countval['num'];
        }
        $this->assign('shopcount',$shopcount);


        $nav = $this->generateTree($tmp);
        $this->assign('nav',$nav);
        // 页面公共继承模版渲染到前台，大C方法：ThinkPHP用于设置、获取，以及保存配置参数的方法
        $this->assign('home_public_template', C('HOME_PUBLIC_TEMPLATE'));

        $link = M('friendlink');
        $data = $link->where("status = 1")->limit(6)->select();
        $this->assign('data',$data);
    }

    /**
     * 超牛逼无限极分类生成树方法
     * @param  [array] $items [无限极分类二维数组]
     * @return [array]        [多维数组]
     * @author Weiliqiang <[<email address>]>
     */
    function generateTree($items)
    {
        $tree = array();
        foreach($items as $item){
            if(isset($items[$item['pid']])){
                $items[$item['pid']]['son'][] = &$items[$item['id']];
            }else{
                $tree[] = &$items[$item['id']];
            }
        }
        return $tree;
    }

    /**
     * 用户登录检测
     * @return [type] [description]
     * @author Weiliqiang <[<email address>]>
     */
    protected function login()
    {
      /* 用户登录检测 */
      is_login() || $this->error('您还没有登录，请先登录！', U('User/login'));
    }

    protected function cheksession(){

        $homeuser = I('session.')['onethink_home']['homeuser'];
        $user_id = I('session.')['onethink_home']['user_id'];
        if ( $homeuser && $user_id) {
            return array('homeuser' => $homeuser , 'user_id' => $user_id , 'decide' => 1);
        }else{
            return array('decide' => 0);
        }
    }


}
